package com.foreveross.crawl.adapter.sub.impl20140402.v3.airfrance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dayatang.excel.ExcelException;

import com.foreveross.crawl.adapter.sub.impl20140402.v3.AirfranceAdapterV3.CabinType;
import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.domain.airfreight.CabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.CabinRelationEntity;
import com.foreveross.crawl.domain.airfreight.doub.DoublePlaneInfoEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnCabinEntity;
import com.foreveross.crawl.domain.airfreight.doub.ReturnDoublePlaneInfoEntity;
import com.foreveross.taskservice.common.bean.TaskModel;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 法国航空往返
 * 
 * @author guanlisha@foreveross.com
 * @date 2014-12-15
 */
@SuppressWarnings("deprecation")
public class AirfranceRoundV3 {
	private static Map<List<String>, DoublePlaneInfoEntity> map = Maps.newConcurrentMap();
	private static Map<List<String>, ReturnDoublePlaneInfoEntity> reMap = Maps.newConcurrentMap();
	private Log logger = LogFactory.getLog(AirfranceRoundV3.class);
	public AirfranceRoundV3() {
	}

	@SuppressWarnings("unchecked")
	public List<DoublePlaneInfoEntity> flightInfoAssembly(String flightListPage, CabinType cabin,TaskModel taskQueue) {
		String flightTypeNos = RegHtmlUtil.regStr(flightListPage, "getUpsellForPreSelectedDate\\((\\{\".*\\}),.indexTabSelected");
		if(flightTypeNos !=null){
			List<Map<String, Object>> outboundsData = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> inboundsData = new ArrayList<Map<String, Object>>();
			DoublePlaneInfoEntity dpie = null;
			ReturnDoublePlaneInfoEntity rdpe = null;
			
			List<DoublePlaneInfoEntity> results = Lists.newArrayList();
			// 数据解析封装
			flightInfoAnalysis(outboundsData,inboundsData, flightTypeNos, cabin);
			// 数据组装
			for (Map<String, Object> outbound:outboundsData) {
				List<String> key = new ArrayList<String>();
				DoublePlaneInfoEntity t = null;
				dpie = AirfranceUtils2.flightBaseInfoAssembly(outbound, taskQueue);
				for(int kl = 0;kl <dpie.getTransits().size();kl++) {
					key.add(dpie.getTransits().get(kl).getCarrierKey()+dpie.getTransits().get(kl).getFlightNo());
				}
				// 用Map过滤相同航班
				t = map.get(key);
				if (t == null) {
					t = dpie;
					map.put(key, t);
				}
				String goTax = RegHtmlUtil.regStr(flightListPage, "您的去程航班.*?taxes&quot;>(.*?)</span>").replace(" ", "");
				Set<CabinEntity> cabinCe = AirfranceUtils2.cabinInfoAssembly(outbound, t.getCabins(), CabinEntity.class, cabin.getLable());
				for(CabinEntity rce : cabinCe) {
					if(!goTax.equals(null)) {
						rce.setTaxesPrice(Double.parseDouble(goTax));
					}
					t.getCabins().add(rce);
				}
				List<CabinEntity> list = new ArrayList(t.getCabins());
				double maxPrice = list.get(0).getPrice();
				//最高价
				for(int c = 1;c<list.size();c++) {
					if(maxPrice < list.get(c).getPrice()) {
						maxPrice = list.get(c).getPrice();
					}
				}
				double minPrice = list.get(0).getPrice();
				//最低价
				for(int c = 1;c<list.size();c++) {
					if(minPrice > list.get(c).getPrice()) {
						minPrice = list.get(c).getPrice();
					}
				}
				t.setTotalHighestPrice(maxPrice);
				t.setTotalHighestTaxesPrice(Double.parseDouble(goTax));
				t.setSumHighestPrice(maxPrice+Double.parseDouble(goTax));
				t.setTotalLowestPrice(minPrice);
				t.setTotalLowestTaxesPrice(Double.parseDouble(goTax));
				t.setSumLowestPrice(minPrice+Double.parseDouble(goTax));
				
				//回程
				for (Map<String, Object> inbound : inboundsData) {
					ReturnDoublePlaneInfoEntity rt = null;
					rdpe = AirfranceUtils2.flightReturnBaseInfoAssembly(inbound, taskQueue);
					List<String> reKey = new ArrayList<String>();
					for(int kl = 0;kl <rdpe.getReturnTransits().size();kl++) {
						reKey.add(rdpe.getReturnTransits().get(kl).getCarrierKey()+rdpe.getReturnTransits().get(kl).getFlightNo());
					}
					// 用Map过滤相同航班
					rt = reMap.get(reKey);
					if (rt == null) {
						rt = rdpe;
						reMap.put(reKey, rt);
					}
					
					String returnTax = RegHtmlUtil.regStr(flightListPage, "您的返程航班.*?taxes&quot;>(.*?)</span>").replace(" ", "");
					Set<ReturnCabinEntity> reCabinCe = AirfranceUtils2.cabinInfoAssembly(inbound, rt.getReturnCabins(), ReturnCabinEntity.class, cabin.getLable());
					for(ReturnCabinEntity rce : reCabinCe) {
						if(!returnTax.equals(null)) {
							rce.setTaxesPrice(Double.parseDouble(returnTax));
						}
						rt.getReturnCabins().add(rce);
					}
					List<ReturnCabinEntity> reList = new ArrayList(rt.getReturnCabins());
					double maxRePrice = reList.get(0).getPrice();
					//最高价
					for(int c = 1;c<reList.size();c++) {
						if(maxRePrice < reList.get(c).getPrice()) {
							maxRePrice = reList.get(c).getPrice();
						}
					}
					double minRePrice = reList.get(0).getPrice();
					//最低价
					for(int c = 1;c<reList.size();c++) {
						if(minRePrice > reList.get(c).getPrice()) {
							minRePrice = reList.get(c).getPrice();
						}
					}
					rt.setTotalHighestPrice(maxRePrice);
					rt.setTotalHighestTaxesPrice(Double.parseDouble(returnTax));
					rt.setSumHighestPrice(maxRePrice+Double.parseDouble(returnTax));
					rt.setTotalLowestPrice(minRePrice);
					rt.setTotalLowestTaxesPrice(Double.parseDouble(returnTax));
					rt.setSumLowestPrice(minRePrice+Double.parseDouble(returnTax));
					t.getReturnPlaneInfos().add(rt);
					analyzeCabinRelation(t, cabinCe, reCabinCe,Double.parseDouble(goTax),Double.parseDouble(returnTax));
				}
			}
			results = new ArrayList<DoublePlaneInfoEntity>(map.values());
			return results;
		}
		throw new ExcelException("解析失败!!!");
	}
	
	private void flightInfoAnalysis (List<Map<String, Object>> outboundsData, List<Map<String, Object>> inboundsData, String doc, CabinType cabin) {
		JSONObject jsonObject = new JSONObject();
		JSONObject jsonObject2 = jsonObject.fromObject(doc);
		JSONArray upsellList = jsonObject2.getJSONArray("upsellList");
		JSONArray upsellListBack =jsonObject2.getJSONArray("upsellListBack");
		Map<String, Object> outboundData = null;
		Map<String, Object> inboundData = null;
		List<Map<String, String>> outboundTransits = null;
		List<Map<String, String>> outboundNoTransits = null;
		List<Map<String, String>> inboundTransits= null;
		Map<String, String> outboundTransit = null;
		Map<String, String> inboundTransit = null;
		//去程
		for (int i = 0;i < upsellList.size(); i++) {
			JSONObject jsonObject3 = upsellList.getJSONObject(i);
			JSONArray listPrices = jsonObject3.getJSONArray("listPrices");//价格
			JSONArray listFlightFeatures = jsonObject3.getJSONArray("listFlightFeatures");//飞机信息
			outboundData = new HashMap<String, Object>();
			outboundTransits = new ArrayList<Map<String,String>>();
			outboundNoTransits = new ArrayList<Map<String,String>>();
			for (int j = 0; j <listFlightFeatures.size();j++) {
				outboundTransit = new HashMap<String, String>();
				JSONObject listFlightFeature = listFlightFeatures.getJSONObject(j);
				outboundTransit.put("flightNo", listFlightFeature.getString("flightCarrier")+listFlightFeature.getString("flightNumber"));
				outboundTransit.put("priceFormatted", listPrices.getJSONObject(0).getString("priceFormatted"));
				outboundTransit.put("company", listFlightFeature.getString("operator"));
				outboundTransit.put("flightType", listFlightFeature.getString("planeType"));
				outboundTransit.put("cabinName", listFlightFeature.getString("commercialClass"));
				outboundTransit.put("flightCarrier", listFlightFeature.getString("flightCarrier"));//"AF"
				// 开始时间与地址
				outboundTransit.put("fromDate", listFlightFeature.getString("departureDateFormatted"));
				outboundTransit.put("fromAddress", listFlightFeature.getString("departureCity"));
				outboundTransit.put("fromAddressCode", listFlightFeature.getString("departureCode"));
				
				// 结束时间与地址
				outboundTransit.put("toDate", listFlightFeature.getString("arrivalDateFormatted"));
				outboundTransit.put("toAddress", listFlightFeature.getString("arrivalCity"));
				outboundTransit.put("toAddressCode",listFlightFeature.getString("arrivalCode"));
				outboundData.put("duration", jsonObject3.getString("duration"));
				
				outboundTransits.add(outboundTransit);
			}
			
			outboundData.put("transits", outboundTransits);
			
			outboundsData.add(outboundData);
		}
		
		logger.info("======================返程=====================");
		
		for (int k = 0;k < upsellListBack.size(); k++) {
			JSONObject jsonObject3 = upsellListBack.getJSONObject(k);
			JSONArray listPrices = jsonObject3.getJSONArray("listPrices");//价格
			JSONArray listFlightFeatures = jsonObject3.getJSONArray("listFlightFeatures");//飞机信息
			inboundData = new HashMap<String, Object>();
			inboundTransits = new ArrayList<Map<String,String>>();
			
			for (int j = 0; j <listFlightFeatures.size();j++) {
				inboundTransit = new HashMap<String, String>();
				JSONObject listFlightFeature = listFlightFeatures.getJSONObject(j);
				inboundTransit.put("priceFormatted", listPrices.getJSONObject(0).getString("priceFormatted"));
				inboundTransit.put("flightNo", listFlightFeature.getString("flightCarrier")+listFlightFeature.getString("flightNumber"));
				inboundTransit.put("company", listFlightFeature.getString("operator"));
				inboundTransit.put("flightType", listFlightFeature.getString("planeType"));
				inboundTransit.put("cabinName", listFlightFeature.getString("commercialClass"));
				inboundTransit.put("flightCarrier", listFlightFeature.getString("flightCarrier"));//"AF"
				// 开始时间与地址
				inboundTransit.put("fromDate", listFlightFeature.getString("departureDateFormatted"));
				inboundTransit.put("fromAddress", listFlightFeature.getString("departureCity"));
				inboundTransit.put("fromAddressCode", listFlightFeature.getString("departureCode"));
				
				// 结束时间与地址
				inboundTransit.put("toDate", listFlightFeature.getString("arrivalDateFormatted"));
				inboundTransit.put("toAddress", listFlightFeature.getString("arrivalCity"));
				inboundTransit.put("toAddressCode", listFlightFeature.getString("arrivalCode"));
				inboundData.put("duration", jsonObject3.getString("duration"));
				
				inboundTransits.add(inboundTransit);
			}
			inboundData.put("transits", inboundTransits);
			inboundsData.add(inboundData);
		}
	}
	
	
	/**
	 * 获取详细页面
	 * 
	 * @param form
	 * @param outbound
	 * @param inbound
	 */
	private void analyzeCabinRelation(DoublePlaneInfoEntity dpie, Set<CabinEntity> cabins, Set<ReturnCabinEntity> returnCabins,Double goTax,Double returnTax) {
		// 设置仓位对应关系
		for (CabinEntity cabin : cabins) {
			for (ReturnCabinEntity rcabin : returnCabins) {
				CabinRelationEntity cre = new CabinRelationEntity();
				cre.setCabinId(cabin.getId());
				cre.setReturnCabinId(rcabin.getId());
				cre.setFullPrice(cabin.getPrice() + rcabin.getPrice() );
				cre.setTotalFullPrice(cabin.getPrice() + rcabin.getPrice()+goTax+returnTax);
				cre.setTaxesPrice(goTax+returnTax);
				dpie.getCabinRelations().add(cre);
			}
		}
	}
}
